package com.breaktian.assemble.socket.task;

import com.breaktian.assemble.socket.callback.ListenTcpCallBack;
import com.breaktian.assemble.socket.tcp.TcpServerSocket;
import com.breaktian.assemble.socket.util.Utils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


/**
 * 处理tcp连接
 * */
public class TcpConnectTask implements Runnable {
	private Socket socket;
	private ListenTcpCallBack listenTcpCallBack;
	
	private boolean socketRuning = true;

	public TcpConnectTask(Socket socket, ListenTcpCallBack call){
		this.socket = socket;
		this.listenTcpCallBack = call;
	}

	public void run() {
		if(socket==null) throw new IllegalStateException("socket为null");
		try {
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			DataInputStream dis = new DataInputStream(in);
			DataOutputStream dos = new DataOutputStream(out);
			while(socketRuning){
				Utils.log("循环读取数据");
				//先判断类型
				int type = dis.readInt();
				if(type== TcpServerSocket.SEND_TYPE_DATA){
					Utils.log("接收data数据");
					long len = dis.readLong();
					
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					byte[] buf = new byte[1024];
					long t = 0;
					while(true){
						int c = dis.read(buf);
						bos.write(buf, 0, c);
						t+=c;
						if(t==len) break;
						Utils.log("正在接收数据 "+c+"/"+t);
					}
					Utils.log("接收data数据完毕");
					byte receiveData[] = bos.toByteArray();
					listenTcpCallBack.onRecvData(receiveData);
				}else if(type==TcpServerSocket.SEND_TYPE_UTF){
					Utils.log("接收utf数据，有返回");
					String recv = dis.readUTF();
					String s = listenTcpCallBack.onRecvUTF(recv);
					dos.writeUTF(s);
				}else if(type==TcpServerSocket.SEND_TYPE_UTF_NO_BACK){
					Utils.log("接收utf数据，无返回");
					String recv = dis.readUTF();
					listenTcpCallBack.onRecvUTFNoBack(recv);
				}
			}
			
			
		} catch (Exception e) {
			Utils.log("出现异常socket(socket客户端主动关闭):"+e.getMessage());
				try {
					socketRuning = false;
					if(socket!=null) socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
//			e.printStackTrace();
		}
	}

}
